package zut.edu.cs.network.threads;

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory;

import zut.edu.cs.network.mysql.DBUtil;

import java.io.File; 
import java.io.FileWriter;
import java.sql.SQLException;
import java.util.ArrayList; 
import java.util.List; 
import java.util.concurrent.BlockingQueue;


public class InnerWriter implements Runnable {
	/** 阻塞队列 */ 
	private BlockingQueue<List<String>> blockingQueue; 
	
//	/** 输出文件名 */ 
//	private String outputFileName; 
	
	/** 结束标识 */ 
	private static final List<String> END = new ArrayList<>(); 
	private static final Logger LOG = LoggerFactory.getLogger(InnerWriter.class); 
	
	
	public InnerWriter() {} 
	
	public InnerWriter(BlockingQueue<List<String>> blockingQueue) { 
		this.blockingQueue = blockingQueue; 
	} 
	
	@Override 
	public void run() { 
		List<String> dataGroup = blockingQueue.poll(); 
		if (dataGroup == null) { 
			return; 
		} 
		// 读取到结束标识， 重新入队 
		if (dataGroup.isEmpty()) { 
			blockingQueue.add(END); 
			return; 
	    } 
		for (String line : dataGroup) { 
			String[] str = line.split(" ");
			System.out.println(str[0] + "," + str[1]);
			try {
				DBUtil.getConnection();
				String sql = "insert into book1(bookname,name) values(?,?)";
				Object[] objects = {str[0],str[1]};
				int values = DBUtil.insert(sql, objects);	
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} 
		
		dataGroup.clear(); 
	} 
	
}
